<?php

declare(strict_types=1);

namespace App\Robot\Job;

use App\CustHub\Service\ChSendRecordService;
use Carbon\Carbon;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use function Hyperf\Coroutine\co;

class SendRecordJob extends Job
{
    public array $data;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        $logger = container()->get(LoggerInterface::class);
        $logger->info("延迟任务处理中...",[
            'time' => Carbon::now()->toDateTimeString()
        ]);
        foreach ($this->data as $item){
            co(function () use ($item){
                container()->get(ChSendRecordService::class)->addRecord($item);
            });
        }
        $logger->info("Task processed successfully", ['data' => $this->data]);
    }

    public function failed(array $data, \Throwable $exception)
    {
        $logger = container()->get(LoggerInterface::class);

        $logger->critical("Task failed after max retries", [
            'data' => $data,
            'error' => $exception->getMessage(),
        ]);

        $this->sendAlert($data);
    }

    protected function sendAlert(array $data)
    {
        echo "Alert: Task has failed after maximum retries.\n";
    }
}